import requests
import re
import os
import pandas as pd
from lxml import etree
import time
import random

# cookies = {
#     'wz_uuid': 'X%2Fd1a9ae3b643d9fde8a696f3b4ad4e780',
#     'sensorsdata2015jssdkchannel': '%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D',
#     'Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1750068129',
#     'HMACCOUNT': 'BEB802B689F1A7D4',
#     'smidV2': '20250616180211f2eaa94911b473002d6a41558ca444c90001e144584af32b0',
#     '_bl_uid': 'Iqm6vb4RynRxCIdpzpjL3yafmhIj',
#     'Hm_lvt_8b5ea374777742fd73d0561bd1dfca6d': '1750068132',
#     's_webp': 's',
#     'sensorsdata2015jssdkcross': '%7B%22distinct_id%22%3A%221977830690b4d9-0384aba661e7b3-26011e51-1327104-1977830690c1b34%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk3NzgzMDY5MGI0ZDktMDM4NGFiYTY2MWU3YjMtMjYwMTFlNTEtMTMyNzEwNC0xOTc3ODMwNjkwYzFiMzQifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%221977830690b4d9-0384aba661e7b3-26011e51-1327104-1977830690c1b34%22%7D',
#     'acw_tc': '0ae5a7dc17501314174687500e006e6544a46d4c1139e7116d5f6dc80676f0',
#     'Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1750131421',
#     'accessToken': '',
#     'token': '',
#     'x-web-ip': '171.212.180.39, 119.23.123.178, 47.106.31.169, 100.121.99.163',
#     '.thumbcache_de0d870e3139ba2368b2e7ea8f11063c': 'PVTWIZxMYy/RX9zyWRmkt9QJk7NUZ+s/dz/ZbmHUOcfnajMISpqHq8n4lywras7W7pgWng+kBZKFNtqTX+w/Yw%3D%3D',
#     'Hm_lpvt_8b5ea374777742fd73d0561bd1dfca6d': '1750132162',
# }

# headers = {
#     'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
#     'accept-language': 'zh-CN,zh;q=0.9',
#     'cache-control': 'max-age=0',
#     'priority': 'u=0, i',
#     'referer': 'https://www.qizhidao.com/',
#     'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
#     'sec-ch-ua-mobile': '?0',
#     'sec-ch-ua-platform': '"Windows"',
#     'sec-fetch-dest': 'document',
#     'sec-fetch-mode': 'navigate',
#     'sec-fetch-site': 'same-origin',
#     'sec-fetch-user': '?1',
#     'upgrade-insecure-requests': '1',
#     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
#     # 'cookie': 'wz_uuid=X%2Fd1a9ae3b643d9fde8a696f3b4ad4e780; sensorsdata2015jssdkchannel=%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D; Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd=1750068129; HMACCOUNT=BEB802B689F1A7D4; smidV2=20250616180211f2eaa94911b473002d6a41558ca444c90001e144584af32b0; _bl_uid=Iqm6vb4RynRxCIdpzpjL3yafmhIj; Hm_lvt_8b5ea374777742fd73d0561bd1dfca6d=1750068132; s_webp=s; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%221977830690b4d9-0384aba661e7b3-26011e51-1327104-1977830690c1b34%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk3NzgzMDY5MGI0ZDktMDM4NGFiYTY2MWU3YjMtMjYwMTFlNTEtMTMyNzEwNC0xOTc3ODMwNjkwYzFiMzQifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%221977830690b4d9-0384aba661e7b3-26011e51-1327104-1977830690c1b34%22%7D; acw_tc=0ae5a7dc17501314174687500e006e6544a46d4c1139e7116d5f6dc80676f0; Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd=1750131421; accessToken=; token=; x-web-ip=171.212.180.39, 119.23.123.178, 47.106.31.169, 100.121.99.163; .thumbcache_de0d870e3139ba2368b2e7ea8f11063c=PVTWIZxMYy/RX9zyWRmkt9QJk7NUZ+s/dz/ZbmHUOcfnajMISpqHq8n4lywras7W7pgWng+kBZKFNtqTX+w/Yw%3D%3D; Hm_lpvt_8b5ea374777742fd73d0561bd1dfca6d=1750132162',
# }


cookies = {
    'sajssdk_2015_cross_new_user': '1',
    'sensorsdata2015jssdkchannel': '%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D',
    'wz_uuid': 'X/fe36031e2352d91d31adfe63416a305b',
    'Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1747617767',
    'HMACCOUNT': 'A735DDA42AC02E6E',
    'SSO_SESSION_ID': 'ZWVjOGY0MmYtZDExMi00YWZmLTg4ZWQtZDdlNDVkYjMwMWY0',
    'ticket': 'eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2l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E1TSE5YcHNRdlRiX3VZVXpxUQ.K0Ytme5n24LKre-EXu0nz7CClT1iT2HX_bt_vmFnppc3xwzHCGia43d3WyE3JZVksuo_N5EjcDxj3s3HgI-W8g',
    'accessToken': 'eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi5odVhicExqVDBmTG1STXQ2b1ZPYnZnLkp2R3BYa2FlcHVaN1ZjUHkySjBheVRNVlZyWURSdmhmazREdWhrc2s2RTQwQWZvVDNhZXA0REkyRVF1ek1zekJOZEM2STFqZzJOSTJjRV9GX3VRZlZDNVZDWEFQSmtrS2tMSTZpSW5CM0FjYU82TFNjV2hrUTVva1htN29UTU9SbjZCVWpmcDdyRnl3RG5XRHo2NDRiSm1vT28xMGx2VnFGczM2OUlmeUltVmlfZjFmMU5GaHVYTk1mSzJrd2lVX2xGaUR5YThmd3dLZFpCaG1Wa3NMN3ktWnVMNDIzOWk3aUJYSHpTTkw5NjJSZVI1aTBPNjJyeEk1SUZmeWtrS0IuRGd4aE1TSE5YcHNRdlRiX3VZVXpxUQ.K0Ytme5n24LKre-EXu0nz7CClT1iT2HX_bt_vmFnppc3xwzHCGia43d3WyE3JZVksuo_N5EjcDxj3s3HgI-W8g',
    'creditNo': '%22%22',
    'param_sign': 'roYuB3',
    'Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1747619300',
    'smidV2': '202505191016307c10a18d5e8a15a50dda3fc1039d489f00ea7a21ddcd9e570',
    '_bl_uid': 'smmtqayquXdgR4fq7006g2h9IX2I',
    'Hm_lvt_8b5ea374777742fd73d0561bd1dfca6d': '1747620994',
    'acw_tc': 'f5d36357174762107277210433481bd19eb244908197885b08a7a18a2916d7',
    'sensorsdata2015jssdkcross': '%7B%22distinct_id%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%2C%22first_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk2ZTYyMmQ3YzJlN2MtMDI4N2Y4YjIxYzgzYzFlLTI2MDExZjUxLTEzMjcxMDQtMTk2ZTYyMmQ3YzMxYjA1IiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiZjdiMWRjYzBkZGJmNDU1ZDgzM2ZhOTk0MTRmMjc4MGUifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%7D%2C%22%24device_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%7D',
    'x-web-ip': '171.218.206.136, 47.121.110.187, 47.106.31.167, 100.121.99.209',
    '.thumbcache_de0d870e3139ba2368b2e7ea8f11063c': 'hZVjd47Cv1sJHhGMmTvVn0f9DpivVn6IF/IytbVBOsjFSd0QEKKRar19TbnFCtp96Hi7/tlo0p6ovKPk4j5lOw%3D%3D',
    'Hm_lpvt_8b5ea374777742fd73d0561bd1dfca6d': '1747621872',
}

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'max-age=0',
    'priority': 'u=0, i',
    'referer': 'https://qiye.qizhidao.com/lib/a01b00c00d00e00f00g00h00i00k00/sc2d10dc5af79548fbff85fbd1b22bf982/',
    'sec-ch-ua': '"Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
    # 'cookie': 'sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkchannel=%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D; wz_uuid=X/fe36031e2352d91d31adfe63416a305b; Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd=1747617767; HMACCOUNT=A735DDA42AC02E6E; SSO_SESSION_ID=ZWVjOGY0MmYtZDExMi00YWZmLTg4ZWQtZDdlNDVkYjMwMWY0; ticket=eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi5odVhicExqVDBmTG1STXQ2b1ZPYnZnLkp2R3BYa2FlcHVaN1ZjUHkySjBheVRNVlZyWURSdmhmazREdWhrc2s2RTQwQWZvVDNhZXA0REkyRVF1ek1zekJOZEM2STFqZzJOSTJjRV9GX3VRZlZDNVZDWEFQSmtrS2tMSTZpSW5CM0FjYU82TFNjV2hrUTVva1htN29UTU9SbjZCVWpmcDdyRnl3RG5XRHo2NDRiSm1vT28xMGx2VnFGczM2OUlmeUltVmlfZjFmMU5GaHVYTk1mSzJrd2lVX2xGaUR5YThmd3dLZFpCaG1Wa3NMN3ktWnVMNDIzOWk3aUJYSHpTTkw5NjJSZVI1aTBPNjJyeEk1SUZmeWtrS0IuRGd4aE1TSE5YcHNRdlRiX3VZVXpxUQ.K0Ytme5n24LKre-EXu0nz7CClT1iT2HX_bt_vmFnppc3xwzHC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UR5YThmd3dLZFpCaG1Wa3NMN3ktWnVMNDIzOWk3aUJYSHpTTkw5NjJSZVI1aTBPNjJyeEk1SUZmeWtrS0IuRGd4aE1TSE5YcHNRdlRiX3VZVXpxUQ.K0Ytme5n24LKre-EXu0nz7CClT1iT2HX_bt_vmFnppc3xwzHCGia43d3WyE3JZVksuo_N5EjcDxj3s3HgI-W8g; creditNo=%22%22; param_sign=roYuB3; Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd=1747619300; smidV2=202505191016307c10a18d5e8a15a50dda3fc1039d489f00ea7a21ddcd9e570; _bl_uid=smmtqayquXdgR4fq7006g2h9IX2I; Hm_lvt_8b5ea374777742fd73d0561bd1dfca6d=1747620994; acw_tc=f5d36357174762107277210433481bd19eb244908197885b08a7a18a2916d7; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%2C%22first_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk2ZTYyMmQ3YzJlN2MtMDI4N2Y4YjIxYzgzYzFlLTI2MDExZjUxLTEzMjcxMDQtMTk2ZTYyMmQ3YzMxYjA1IiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiZjdiMWRjYzBkZGJmNDU1ZDgzM2ZhOTk0MTRmMjc4MGUifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%7D%2C%22%24device_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%7D; x-web-ip=171.218.206.136, 47.121.110.187, 47.106.31.167, 100.121.99.209; .thumbcache_de0d870e3139ba2368b2e7ea8f11063c=hZVjd47Cv1sJHhGMmTvVn0f9DpivVn6IF/IytbVBOsjFSd0QEKKRar19TbnFCtp96Hi7/tlo0p6ovKPk4j5lOw%3D%3D; Hm_lpvt_8b5ea374777742fd73d0561bd1dfca6d=1747621872',
}


def check_intellectual_property(url):
    repose = requests.get(cookies=cookies, headers=headers, url=url)
    # print(repose.text)
    if repose.status_code == 200:
        return True
    else:
        return False


def get_uuid(url):
    repose = requests.get(cookies=cookies, headers=headers, url=url)

    pattern = r'\(\s*[^)]*?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})[^)]*?\)'

    matches = re.findall(pattern, repose.text)
    if matches == []:
        with open('./只有软著报错url.txt', 'a+', encoding='utf-8') as f:
            f.write(f'{url}\n')
        return False
    return matches[0]


def get_Credit_code(url):

    repose = requests.get(cookies=cookies, headers=headers, url=url)
    tree = etree.HTML(repose.text)

    Companyname_number = tree.xpath(
        '//div[@class="copy-box initialShowCopyIcon"]/span/span[@class="text-num"]/text()')[0]
    return Companyname_number


def write_zhuanli(items):

    file_exists = os.path.exists('./invebt_number_zhunali.csv')
    df = pd.DataFrame(
        items, columns=['发明授权', '实用新型', '外观设计', '总和', '社会信用统一代码'])
    df.to_csv('invebt_number_zhunali.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("专利信息数据已追加到 invebt_number_zhunali.csv")


def write_rj(items):

    file_exists = os.path.exists('./invebt_number_rj.csv')
    df = pd.DataFrame(
        items, columns=['软件数量', '社会信用统一代码'])
    df.to_csv('invebt_number_rj.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("软件著作权数据已追加到 invebt_number_rj.csv")


def get_patent_number(uuid, lll):
    invent_auth_count = 0
    utility_model_count = 0
    exterior_design = 0
    all_number = 0
    for i in range(2022, 2026):
        json_data_patent = {
            'eid': uuid,
            'apy': i,
            'authority': '',
            'lsc': '授权',
            'pdt': '',
            'pdy': '',
        }

        response = requests.post(
            'https://app.qizhidao.com/qzd-bff-enterprise/qzd/v1/enterprise/pc/patentFilterResult',
            cookies=cookies,
            headers=headers,
            json=json_data_patent,
        )
        print(111111)
        print(response.text)
        data = response.json()

        if data['data']['PDT'] == []:
            invent_auth_count += 0
            utility_model_count += 0
            exterior_design += 0
            continue

        for i in data['data']['PDT']:
            if i['key'] == '发明授权':
                invent_auth_count += int(i['doc_count'])
            elif i['key'] == '实用新型':
                utility_model_count += int(i['doc_count'])
            elif i['key'] == '外观设计':
                exterior_design += int(i['doc_count'])
    all_number = invent_auth_count+utility_model_count+exterior_design
    return [[invent_auth_count, utility_model_count, exterior_design, all_number, lll]]


def get_soft_number(rj_code, uuid, lll):
    num = 0
    for i in rj_code:
        json_data = {
            'type': 'S',
            'eid': uuid,
            'registerDate': i,
        }

        response = requests.post(
            'https://app.qizhidao.com/qzd-bff-enterprise/qzd/v11/es/enterprise/pc/getCopyrightsCondition',
            cookies=cookies,
            headers=headers,
            json=json_data,
        )
        print(i)
        data = response.json()
        print(data)
        num += int(data['data']['registerDate'][0]['num'])
    return [[num, lll]]


def get_registerDate(uuid):
    json_data = {
        'type': 'S',
        'eid': uuid,
    }
    response = requests.post(
        'https://app.qizhidao.com/qzd-bff-enterprise/qzd/v11/es/enterprise/pc/getCopyrightsCondition',
        cookies=cookies,
        headers=headers,
        json=json_data,
    )

    data = response.json()
    date_list = []
    if data['data']['registerDate'] == []:
        return False
    for i in data['data']['registerDate']:
        if i['name'] >= '2022':
            date_list.append(i['key'])
    return date_list


def main():
    with open("./url_value.txt", "r", encoding="utf-8") as file:
        urls = [url.strip() for url in file.readlines()]

    url_count = 0
    for url in urls:
        # 每10个URL休息一次
        if url_count > 0 and url_count % 10 == 0:
            sleep_time = random.uniform(5, 10)  # 随机等待5-10秒
            print(f"已爬取{url_count}个URL，休息{sleep_time:.2f}秒...")
            time.sleep(sleep_time)

        # 每次请求前随机等待0.5-2秒
        request_sleep = random.uniform(0.5, 2)
        time.sleep(request_sleep)

        url_change = url.replace("/company/", "/property/")
        if check_intellectual_property(url_change):
            # 获得uuid
            uuid = get_uuid(url_change)
            if uuid:
                pass
            else:
                print('uuid获取错误')
                continue
            # 获得社会统一代码
            lll = get_Credit_code(url)
            # 获得专利数量
            '''
                try:
                    result = get_patent_number(uuid, lll)
                except:
                    result = [[0,0,0,lll]]
            '''

            # 只获取软著权
            result = [[0, 0, 0, 0, lll]]

            # 获得registerDate-----软件著作权数量载荷需要的参数
            rj_dade = get_registerDate(uuid)
            if rj_dade == False:
                with open('./最新知识产权.txt', 'a+', encoding='utf-8') as f:
                    f.write(f'{url}\n')
                print(f'{url}可能是最新的知识产权！！')
                continue
            if rj_dade == []:
                rj_result = [[0, lll]]
                write_rj(rj_result)
            else:
                rj_result = get_soft_number(rj_dade, uuid, lll)
                write_rj(rj_result)

            write_zhuanli(result)

        url_count += 1
        # break


if __name__ == "__main__":
    main()
